package sisicotren.model.simulator.test.junit;

import junit.framework.TestCase;
import org.junit.Test;

import sisicotren.model.simulator.Channel;
import sisicotren.model.simulator.Client;
import sisicotren.model.simulator.ClientsInjector;
import sisicotren.model.simulator.Queue;
import sisicotren.model.simulator.System;
import java.util.LinkedList;
import java.util.List;

public class ClientsInjectorTestCase extends TestCase {

	@Test public void testAddClientsInQueue() {
		
		Double cliPerMin = 50.00;
		Double channelRate = 65.00;
		int totalQueues = 1;
		int totalChannels = 5;
		List<Channel> channels = new LinkedList<Channel>();
		for(int j=0; j<totalChannels; j++)
			channels.add(new Channel(channelRate));
		
		// colas ilimitadas
		List<Queue<Client>> queues = new LinkedList<Queue<Client>>();
		for(int i=0; i<totalQueues; i++) 
			queues.add(new Queue<Client>());
		
		System system = new System(queues, channels);
		ClientsInjector inj = new ClientsInjector(cliPerMin, system);
		long startTime = java.lang.System.currentTimeMillis();
		Thread injThread = new Thread(inj);
		
		// simulacion de 1 minuto.
		long endTime = startTime + 60 * 1000;
		injThread.start();
		while(java.lang.System.currentTimeMillis() < endTime )
			Thread.yield();
		
		// dejo de inyectar clientes.
		inj.stop();
		
		java.lang.System.out.println("Clientes injectados : " + system.getTotalClientsInjected());
		
		// espero a que se vacien todas las colas.
		boolean clientsInQueue = true;
		while(clientsInQueue) {
			Thread.yield();
			int clients = 0;
			for(int i=0; i<system.getQueues().size(); i++) {
				clients += system.getQueues().get(i).size();
			}
			clientsInQueue = clients > 0 ? true : false;
		}
		
		int totalServedClients = 0;
		for(int j=0; j<totalChannels; j++)
			totalServedClients += channels.get(j).getServedClients().size();
		
		java.lang.System.out.println("Clientes Atendidos  : " + totalServedClients);
		
		// error tolerable de +-10
		assertTrue(60 > system.getTotalClientsInjected() && system.getTotalClientsInjected() > 40);
		// todos los clientes inyectados deben ser atendidos.
		assertEquals(totalServedClients, system.getTotalClientsInjected().intValue());
	}
	
}
